#include "MIDIUSB.h"

int LDR_PIN = 2;
int valueLDR = 0;
int lastValueLDR = 0;

//MIDI NOTE
void noteOn(byte channel, byte pitch, byte velocity) {
  midiEventPacket_t noteOn = {0x09, 0x90 | channel, pitch, velocity};
  MidiUSB.sendMIDI(noteOn);
}

void noteOff(byte channel, byte pitch, byte velocity) {
  midiEventPacket_t noteOff = {0x08, 0x80 | channel, pitch, velocity};
  MidiUSB.sendMIDI(noteOff);
}


void setup() {
  // put your setup code here, to run once:
  pinMode(LDR_PIN, INPUT);
  Serial.begin(9600);
}

void loop() {
  // put your main code here, to run repeatedly:
  valueLDR = digitalRead(LDR_PIN);

  // 当值产生了变化时
  if (lastValueLDR != valueLDR) {
    Serial.println(valueLDR);

    if (valueLDR == 0) {
      noteOn(0, 48, 64);   // Channel 0, middle C, normal velocity
      MidiUSB.flush();
    }

    if (valueLDR == 1) {
      noteOff(0, 48, 64);  // Channel 0, middle C, normal velocity
      MidiUSB.flush();
    }

    lastValueLDR = valueLDR;
    delay(50);
  }
}